package brau.view;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.w3c.ddr.simple.PropertyValue;

import brau.business.EnderecoBC;
import brau.domain.Endereco;
import brau.view.singleton.DdrSingleton;

@ManagedBean(name="ddrMB")
@SessionScoped
public class DdrMB implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private EnderecoBC bc;

	private Endereco endereco = new Endereco();
	
	private List<PropertyValue> listDdr = new ArrayList<PropertyValue>();
	
	private StreamedContent imagemRedimensionada = null;
    
    private Integer displayWidth = 250;
    private Integer displayHeight = 0;
    private String imageRelativePath = "images/fotos";
    private String imageName = "img_0182.jpg";
    private Integer imageWidth = 0;
    private Integer imageHeight = 0;
    private Integer imageSise = 0;
    private String vendor = "";
    private Double fatorReducao = 0.90;  //90%

    
    public DdrMB() {
    	if (listDdr.size() == 0) DdrSingleton.getInstance().carregarListDdr(getUserAgent(),listDdr);
    	
    	String strWidth = DdrSingleton.getInstance().getStringValueByName("displayWidth", listDdr);
    	setDisplayWidth((int) (Integer.parseInt( (strWidth == null ? "800" : strWidth) )*fatorReducao));

    	String strHeight = DdrSingleton.getInstance().getStringValueByName("displayHeight", listDdr);
    	setDisplayHeight((int) (Integer.parseInt( (strWidth == null ? "600" : strHeight) )*fatorReducao));

    	vendor  = DdrSingleton.getInstance().getStringValueByName("vendor", listDdr);
    	
		if ( imagemRedimensionada == null ) carregarImagemRedimensionada();
    }  

    
    public String getUserAgent() { 
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		return ((HttpServletRequest)request).getHeader("User-Agent");
    }
    
    
    
    public void carregarImagemRedimensionada() {
    	
        String imageLoc = FacesContext.getCurrentInstance().getExternalContext().getRealPath(imageRelativePath)+"/"+imageName;
        
        try {
        	
        	// Lê a imagem original localizada no servidor
            BufferedImage bufferedImage = ImageIO.read(new File(imageLoc));
            
            // Redimensiona a Imagem, calculando a altura proporcionalmente à largura em relação ao tamanho original
            BufferedImage newImage = createResizedCopy(bufferedImage, getDisplayWidth(), (getDisplayWidth() * bufferedImage.getHeight() / bufferedImage.getWidth())); 

            setImageWidth(newImage.getWidth());
            setImageHeight(newImage.getHeight());
 
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(newImage, "jpg", os);
            
            imageSise = os.size();
            
            imagemRedimensionada = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/jpeg", imageName);
  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    	
    }
    
    private BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight) {
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = scaledBI.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        g.dispose();
        return scaledBI;
    }

    
	public void gravarEnderecoGmap() {
		endereco.setSituacao(1);
		this.bc.gravarEnderecoGmap(endereco);
	}
   
    
	
	// getters and setters
    

    public Endereco getEndereco() {
		return endereco;
	}
	public void setEndereco(Endereco endereco) {
		this.endereco = endereco;
	}
    

    public StreamedContent getImagemRedimensionada() {
    	//TODO pesquisar a razão do componente <p:graphicImage perder a referência para este StreamedContent
    	carregarImagemRedimensionada();
		return imagemRedimensionada;
	}
	

	public void setImagemRedimensionada(StreamedContent imagemRedimensionada) {
		this.imagemRedimensionada = imagemRedimensionada;
	}

	public List<PropertyValue> getListDdr() {
		return listDdr;
	}

	
	public Integer getDisplayWidth() {
		return displayWidth;
	}
	public void setDisplayWidth(Integer displayWidth) {
		this.displayWidth = displayWidth;
	}

	
	public Integer getDisplayHeight() {
		return displayHeight;
	}
	public void setDisplayHeight(Integer displayHeight) {
		this.displayHeight = displayHeight;
	}

	
	public String getImageRelativePath() {
		return imageRelativePath;
	}
	public void setImageRelativePath(String imageRelativePath) {
		this.imageRelativePath = imageRelativePath;
	}

	
	public String getImageName() {
		return imageName;
	}
	public void setImageName(String imageName) {
		this.imageName = imageName;
	}

	
	public Integer getImageWidth() {
		return imageWidth;
	}
	public void setImageWidth(Integer imageWidth) {
		this.imageWidth = imageWidth;
	}

	
	public Integer getImageHeight() {
		return imageHeight;
	}
	public void setImageHeight(Integer imageHeight) {
		this.imageHeight = imageHeight;
	}

	
	public Integer getImageSise() {
		return imageSise;
	}
	public void setImageSise(Integer imageSise) {
		this.imageSise = imageSise;
	}

	
	public String getVendor() {
		return vendor;
	}
	public void setVendor(String vendor) {
		this.vendor = vendor;
	}


}
